package demo.dcs.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * @author buffoon
 * @date 16/1/19
 */
public class LinuxShellUtil {

    private static final Logger logger = LoggerFactory.getLogger(LinuxShellUtil.class);

    /**
     * 执行linux命令
     *
     * @param cmd
     */
    public static String exec(String cmd) {
        LineNumberReader lineNumberReader = null;
        Process process = null;
        try {
            String[] cmdA = {"/bin/sh", "-c", cmd};
            process = Runtime.getRuntime().exec(cmdA);
            lineNumberReader = new LineNumberReader(new InputStreamReader(process.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = lineNumberReader.readLine()) != null) {
                sb.append(StringUtils.trim(line));
            }
            return sb.toString();
        } catch (Exception e) {
            logger.error("LinuxShellUtil run shell {} error", cmd, e);
            return null;
        } finally {
            if (lineNumberReader != null) {
                try {
                    lineNumberReader.close();
                } catch (Exception e) {
                    logger.error("LinuxShellUtil close lineNumberReader error {}", e.getMessage());
                }
            }
            if (process != null) {
                try {
                    process.waitFor();
                } catch (Exception e) {
                    logger.error("LinuxShellUtil close process error {}", e.getMessage());
                }
                process.destroy();
            }
        }
    }

}
